package com.zhixiang.xaec.action.system;


import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;

import com.zhixiang.core.util.StringUtil;
import com.zhixiang.core.web.action.BaseAction;
import com.zhixiang.xaec.entity.system.AppUser;
import com.zhixiang.xaec.service.system.AppUserService;


@Controller
@Scope("prototype")
public class LoginAction extends BaseAction implements Serializable
{
    private static final long serialVersionUID = 3167386045436140019L;

    private AppUser user;

    private String username;

    private String password;

    private String checkCode;

    private String key = "RememberAppUser";

    @Resource(type = AppUserService.class)
    private AppUserService userService;

    @Resource(type = AuthenticationManager.class)
    private AuthenticationManager authenticationManager = null;

    public String login()
    {
//        StringBuffer localStringBuffer = new StringBuffer("{msg:'");
        // Captcha localCaptcha = (Captcha)getSession().getAttribute(
        // "simpleCaptcha");
        Boolean localBoolean = Boolean.valueOf(false);
        String str1 = null;
        if ((!"".equals(this.username)) && (this.username != null))
        {
            setUser(this.userService.findByUserName(this.username));
            if (this.user != null)
            {
                if (org.apache.commons.lang.StringUtils.isNotEmpty(this.password))
                {
                    str1 = StringUtil.encryptSha256(this.password);
                    if (this.user.getPassword().equalsIgnoreCase(str1))
                    {
                        // 验证码
                        /*
                         * if (localCaptcha == null) { localStringBuffer.append("请刷新验证码再登录.'"); }
                         * else { localStringBuffer.append("验证码不正确.'"); }
                         */
                        localBoolean = true;
                    }
                    else
                    {
//                        localStringBuffer.append("密码不正确.'");
                        setSuccess(false);
                        setMsg("密码不正确");
                    }
                }
                else
                {
//                    localStringBuffer.append("密码不能为空.'");
                    setSuccess(false);
                    setMsg("密码不能为空");
                }
            }
            else
            {
//                localStringBuffer.append(this.username + "用户不存在.'");
                setMsg("用户不存在");
                AppUser appUser = new AppUser();
                appUser.setUserId(Long.valueOf(-1000L));
                appUser.setUsername(this.username);
            }
        }
        if (localBoolean.booleanValue())
        {
            UsernamePasswordAuthenticationToken localUsernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                this.username, this.password);
            SecurityContext localSecurityContext = SecurityContextHolder.getContext();
            try
            {
                localSecurityContext.setAuthentication(this.authenticationManager.authenticate(localUsernamePasswordAuthenticationToken));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            SecurityContextHolder.setContext(localSecurityContext);
            getSession().setAttribute("SPRING_SECURITY_LAST_USERNAME", this.username);
            String str2 = getRequest().getParameter("_spring_security_remember_me");
            if ((str2 != null) && (str2.equals("on")))
            {
                long l1 = 1209600L;
                long l2 = System.currentTimeMillis() + l1 * 1000L;
                String str3 = DigestUtils.md5Hex(this.username + ":" + l2 + ":"
                                                 + this.user.getPassword() + ":" + this.key);
                String str4 = this.username + ":" + l2 + ":" + str3;
                String str5 = new String(Base64.encodeBase64(str4.getBytes()));
                getResponse().addCookie(makeValidCookie(l2, str5));
            }
//            setSuccess(true);
            // setJsonString("{success:true}");
            try
            {
                this.username = URLEncoder.encode(this.username, "UTF-8");
            }
            catch (UnsupportedEncodingException localUnsupportedEncodingException)
            {
                localUnsupportedEncodingException.printStackTrace();
            }
            Cookie localCookie = new Cookie("jforumSSOCookieNameUser", this.username + ","
                                                                       + this.user.getPassword());
            localCookie.setMaxAge(-1);
            localCookie.setPath("/");
            getResponse().addCookie(localCookie);
        }
        else
        {
            //localStringBuffer.append(",failure:true}");
            setSuccess(false);
            //setJsonString(localStringBuffer.toString());
        }
        return SUCCESS;
    }

    protected Cookie makeValidCookie(long paramLong, String paramString)
    {
        HttpServletRequest localHttpServletRequest = getRequest();
        Cookie localCookie = new Cookie("SPRING_SECURITY_REMEMBER_ME_COOKIE", paramString);
        localCookie.setMaxAge(157680000);
        localCookie.setPath(org.springframework.util.StringUtils.hasLength(localHttpServletRequest.getContextPath()) ? localHttpServletRequest.getContextPath() : "/");
        return localCookie;
    }

    public AppUser getUser()
    {
        return this.user;
    }

    public void setUser(AppUser paramAppUser)
    {
        this.user = paramAppUser;
    }

    public String getUsername()
    {
        return this.username;
    }

    public void setUsername(String paramString)
    {
        this.username = paramString;
    }

    public String getPassword()
    {
        return this.password;
    }

    public void setPassword(String paramString)
    {
        this.password = paramString;
    }

    public String getCheckCode()
    {
        return this.checkCode;
    }

    public void setCheckCode(String paramString)
    {
        this.checkCode = paramString;
    }

}
